package com.fulihui.common.util;

import com.google.common.base.Throwables;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 密码工具
 *
 * @author: Levon
 * @version: v 0.1 2017-05-26 15:28
 */
public class PasswordUtil {

    /**
     * 加密用户密码 MD5(SHA256(longId + passwd + salt))
     *
     * @param loginId 登陆账号
     * @param passwd  密码
     * @param salt    盐
     * @return 加密后的密文
     */
    public static String encryptPassword(String loginId, String passwd, String salt) {
        String encrypt = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
            byte[] bytes = md5.digest(sha256.digest((loginId + passwd + salt).getBytes()));
            encrypt = Hex.encodeHexString(bytes);
        } catch (NoSuchAlgorithmException e) {
            Throwables.propagate(e);
        }
        return encrypt;
    }

    /**
     * 验证密码是否正确
     *
     * @param loginId 登陆账号
     * @param passwd  密码
     * @param salt    盐
     * @param saved   已保存的密码
     * @return 匹配结果
     */
    public static boolean passwordsMatch(String loginId, String passwd, String salt, String saved) {
        return StringUtils.equals(encryptPassword(loginId, passwd, salt), saved);
    }

}
